<template>
  <div class="app-container">
    <el-row>
      <div style="margin: 4px 0 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">{{ $route.query.name }}</span>
      </div>
    </el-row>
    <div style="margin: 20px 0px 20px 4px;">
      <span style="font-size: 20px; font-weight: bold">表头信息</span>
    </div>
    <el-card class="box-card">

      <div v-if="chooseHeader !== null">
        <div v-if="chooseHeader.json==null">
          <tenkvHeader ref="Header" :header-form-origin="headerFormOrigin"/>
        </div>
        <div v-else-if="chooseHeader.hasOwnProperty('json')">
          <v-form-render ref="Header" :form-data="headerFormOrigin" :form-json="chooseHeader.json|cleanJson"/>
        </div>
      </div>
    </el-card>
    <el-row>
      <div style="margin: 20px 0px 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">表单项</span>
      </div>
    </el-row>
    <el-card v-loading="listLoading">
      <div v-for="(item,index) in bodyRenderList" :key="index" style="margin: 12px 0;">
        <custom-question-block v-if="item.json==null"
                               v-model="bodyModelValue[`${item.oid}`]"
                               :question-block="item" :order="false"/>
        <v-form-render v-else :form-json="getClearFormJson(item.json)" :form-data="bodyModelValue[`${item.oid}`]"
                       :ref="`${item.oid}`" v-model="bodyModelValue[`${item.oid}`]"/>
      </div>
    </el-card>
    <el-row>
      <div style="margin: 20px 0px 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">表尾信息</span>
      </div>
    </el-row>
    <el-card>
      <div v-if="chooseTail !== null">
        <div v-if="chooseTail.json==null">
          <tenkvTail ref="Tail" :tail-form="tailForm"/>
        </div>
        <div v-else-if="chooseTail.hasOwnProperty('json')">
          <v-form-render ref="Tail" :form-data="tailForm" :form-json="getClearFormJson(chooseTail.json)"/>
        </div>
      </div>
    </el-card>
    <el-row>
      <div style="margin: 20px 0px 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">附件上传</span>
      </div>
    </el-row>
    <el-card style="padding-bottom: 6px;">
      <el-upload
        style="width:500px;"
        class="upload-demo"
        :file-list="fileList"
        :auto-upload="false"
        :on-change="handleChange"
        action="#"
      >
        <el-button slot="trigger" size="small" type="primary">添加文件</el-button>
      </el-upload>
    </el-card>
    <el-row style="margin: 24px 0px 24px 0px;">
      <el-form :inline="true" style="display: flex; justify-content: center;">
        <el-button type="primary" :plain="true" @click="saveAsDraft">保存草稿</el-button>
        <el-button type="primary" @click="submitDialogFormVisible = true">创建并提交</el-button>
        <el-button @click="$router.push({path:'/workOrderSys/myCreation'})">取消</el-button>
      </el-form>
    </el-row>
    <el-dialog title="提交新工单" :visible.sync="submitDialogFormVisible">
      <el-tabs v-model="activeTabName" :stretch="true">
        <el-tab-pane label="作为主工单" name="first">
          <el-form ref="ruleForm" :model="queryUser" status-icon class="demo-ruleForm" style="margin-left: 12px">
            <el-form-item>
              <span>该操作将直接提交工单并进入流转状态，请确认工单是否正确填写。</span>
            </el-form-item>
            <el-form-item label="工单流转至:">
              <el-input v-model="queryUser.keyword" placeholder="请输入姓名或工号" style="width: 200px;"
                        prefix-icon="el-icon-search"
                        size="small"
                        @keyup.enter.native="searchUser(1)"
              />
              <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 12px"
                         @click="searchUser(1)">搜索
              </el-button>
            </el-form-item>
          </el-form>
          <el-table
            v-loading="listLoading"
            :data="searchList"
            style="width: 100%"
          >
            <el-table-column
              label="工号"
              prop="uid"
            />
            <el-table-column
              label="姓名"
              prop="username"
            />
            <el-table-column
              align="right"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleTo(scope.row.uid)"
                >流转给TA
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="width: 100%;text-align: center;margin:24px 0 0 0;">
            <el-pagination
              :page-size="5"
              background
              layout="prev, pager, next"
              :current-page.sync="currentPage"
              :total="total"
              @current-change="searchUser(currentPage)"
            />
          </div>
          <div style="width: 100%;display: flex;margin-top: 24px;">
            <el-button @click="submitDialogFormVisible = false">取消</el-button>
            <div style="flex-grow: 1"></div>
            <el-button type="primary" @click="handleTo($store.getters.userInfo.uid)">流转给自己</el-button>
            <el-button type="primary" @click="handleToStore($store.getters.userInfo.uid)">流转为自由表单</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane active-name="second" label="作为子工单">
          <el-form ref="childForm" :model="queryChildOrder" status-icon class="demo-ruleForm" style="margin-left: 12px">
            <el-form-item>
              <span>该操作将直接提交工单并进入流转状态，请确认工单是否正确填写。</span>
            </el-form-item>
            <el-form-item label="加入主工单:">
              <el-input v-model="queryChildOrder.keyword" placeholder="请输入主工单关键字" style="width: 200px;"
                        prefix-icon="el-icon-search"
                        size="small"
                        @keyup.enter.native="searchMainOrder(childOrderCurrentPage)"
              />
              <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 12px"
                         @click="searchMainOrder(childOrderCurrentPage)">搜索
              </el-button>
            </el-form-item>
          </el-form>
          <el-table
            v-loading="childOrderListLoading"
            :data="childOrderList"
            style="width: 100%"
          >
            <el-table-column
              label="工单编号"
              prop="tid"
            />
            <el-table-column
              label="工单名称"
              prop="name"
            />
            <el-table-column
              align="right"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="submitToMainOrder(scope.row.tid)"
                >作为子工单
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="width: 100%;text-align: center;margin:24px 0 0 0;">
            <el-pagination
              :page-size="5"
              background
              layout="prev, pager, next"
              :current-page.sync="childOrderCurrentPage"
              :total="childOrderTotal"
              @current-change="searchMainOrder(childOrderCurrentPage)"
            />
          </div>
          <div style="width: 100%;display: flex;margin-top: 24px;">
            <el-button @click="submitDialogFormVisible = false">取消</el-button>
            <div style="flex-grow: 1"></div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import CustomRadio from '@/components/CustomRadio'
import {
  addDraft,
  deleteDraft,
  getTemplateBody,
  getTemplateHeader,
  getTemplateList, getTemplateTail,
  publishDraft,
  uploadOrderFile
} from '@/api/table'
import {getClearFormJson, MAPPER, PAGE_SIZES} from '@/utils/common'
import CustomQuestionBlock from '@/components/CustomQuestionBlock'
import {spheader, handleHeader, sptail, headerFormOrigin} from '@/utils/fix/pre'
import {findUser} from '@/api/user'
import {publishDraftAsFree} from '../../api/table'
import {getMyCreatedOrderList, setMainOrder} from "@/api/order";
import tenkvHeader from "@/components/fixedForm/tenkvHeader.vue";
import tenkvTail from "@/components/fixedForm/tenkvTail.vue";

const allComponents = require.context('@/components/CustomQuestionBlock/questions', false, /\.vue$/)
const res_components = {}
allComponents.keys().forEach(fileName => {
  const comp = allComponents(fileName)
  res_components[fileName.replace(/^\.\/(.*)\.\w+$/, '$1')] = comp.default
})
export default {
  components: {tenkvTail, tenkvHeader, CustomRadio, ...res_components, CustomQuestionBlock},
  data() {
    return {
      chooseHeader: null,
      chooseTail: null,
      bodyRenderList: [],
      activeTabName: 'first',
      searchList: [],
      currentPage: 1,
      pageSize: PAGE_SIZES,
      total: 0,
      MAPPER: MAPPER,
      headerFrom: {...spheader},
      tailForm: {...sptail},
      queryUser: {
        keyword: '',
        status: '',
        dateRange: []
      },
      list: [],
      listLoading: true,
      fileList: [],
      headerFormOrigin: JSON.parse(JSON.stringify(headerFormOrigin)),
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      orgNum: '',
      id: '',
      saveDialogFormVisible: false,
      submitDialogFormVisible: false,
      template: {body_list: []},
      bodyModelValue: {},
      // 子工单流转属性
      childOrderListLoading: false,
      childOrderList: [],
      childOrderTotal: 0,
      childOrderCurrentPage: 1,
      childOrderPageSize: PAGE_SIZES,
      queryChildOrder: {
        keyword: '',
      },
      bodyTemplates: [],
      headerTemplates: [],
      tailTemplates: []
    }
  },
  filters: {
    cleanJson(json) {
      return getClearFormJson(json)
    }
  },
  async created() {
    try {
      const [bodyResponse, headerResponse, tailResponse] = await Promise.all([
        getTemplateBody(),
        getTemplateHeader(),
        getTemplateTail()
      ]);
      this.bodyTemplates = bodyResponse.data.data;
      this.headerTemplates = headerResponse.data.data;
      this.tailTemplates = tailResponse.data.data;
      this.fetchData()
    } catch (error) {
      console.error('发生错误：', error);
    }
  },
  methods: {
    getClearFormJson,
    handleChange(file, fileList) {
      this.fileList = fileList
      const isLt5M = file.size / 1024 / 1024 > 20
      if (isLt5M) {
        this.$message.error('超过5MB！')
        const currIdx = this.fileList.indexOf(file)
        this.fileList.splice(currIdx, 1)
      }
    },
    handleToStore(uid) {
      this.getBodyValue()
      const header = this.$refs.Header.getFormData(false)
      this.template.body_list.forEach((item, index) => {
        this.bodyModelValue[item]['num'] = index + 1
      })
      const data = {
        name: header.projectName || header.retData.projectName,
        handler: uid,
        header_id: this.template.header_id,
        header_value: header,
        body_list: this.template.body_list,
        body_value: this.bodyModelValue,
        tail_id: this.template.tail_id,
        tail_value: this.$refs.Tail.getFormData(false)
      }
      addDraft(data).then(async res => {
        const loadingInstance = this.$loading({fullscreen: true})
        console.log(res)
        const tid = res.data.tid
        if (this.fileList.length !== 0) {
          for (const file of this.fileList.map(item => item.raw)) {
            const formData = new FormData()
            formData.append('file', file)
            await uploadOrderFile(formData, tid).then(res => {
            })
            console.log(123)
          }
          await publishDraft(tid).then(res => {
            this.$message.success('发布表单成功')
          }).catch(() => {
            deleteDraft(tid).then(res => {
              console.log(res)
            })
          })
          this.$message.success('添加表单草稿成功')
          setTimeout(() => {
            this.$router.push('/workOrderSys/myDraft')
          }, 500)
        } else {
          publishDraftAsFree(tid).then(res => {
            this.$message.success('发布表单成功')
            setTimeout(() => {
              this.$router.push('/workOrderSys/myCreation')
            }, 500)
          }).catch(() => {
            deleteDraft(tid).then(res => {
              console.log(res)
            })
          })
        }
        loadingInstance.close()
      })
    },
    submitToMainOrder(ftid) {
      this.getBodyValue()
      const header = this.$refs.Header.getFormData(false)
      this.template.body_list.forEach((item, index) => {
        this.bodyModelValue[item]['num'] = index + 1
      })

      const data = {
        name: header.projectName || header.retData.projectName,
        handler: this.$store.getters.id,
        header_id: this.template.header_id,
        header_value: header,
        body_list: this.template.body_list,
        body_value: this.bodyModelValue,
        tail_id: this.template.tail_id,
        tail_value: this.$refs.Tail.getFormData(false)
      }
      addDraft(data).then(async res => {
        const loadingInstance = this.$loading({fullscreen: true})
        const tid = res.data.tid
        if (this.fileList.length !== 0) {
          for (const file of this.fileList.map(item => item.raw)) {
            const formData = new FormData()
            formData.append('file', file)
            await uploadOrderFile(formData, tid).then(res => {
            })
          }
          await publishDraft(tid).then(res => {
            setMainOrder(tid, ftid).then(res => {
              this.$message.success('发布表单成功')
              setTimeout(() => {
                this.$router.push('/workOrderSys/myDraft')
              }, 500)
            })
          }).catch(() => {
            deleteDraft(tid).then(res => {
            })
          })
        } else {
          publishDraft(tid).then(res => {
            setMainOrder(tid, ftid).then(res => {
              this.$message.success('发布表单成功')
              setTimeout(() => {
                this.$router.push('/workOrderSys/myCreation')
              }, 500)
            })
          }).catch(() => {
            deleteDraft(tid).then(res => {
            })
          })
        }
        loadingInstance.close()
      })

    },
    handleTo(uid) {
      this.getBodyValue()
      const header = this.$refs.Header.getFormData(false)
      this.template.body_list.forEach((item, index) => {
        this.bodyModelValue[item]['num'] = index + 1
      })
      const data = {
        name: header.projectName || header.retData.projectName,
        handler: uid,
        header_id: this.template.header_id,
        header_value: header,
        body_list: this.template.body_list,
        body_value: this.bodyModelValue,
        tail_id: this.template.tail_id,
        tail_value: this.$refs.Tail.getFormData(false)
      }
      console.log(data)
      addDraft(data).then(async res => {
        const loadingInstance = this.$loading({fullscreen: true})
        const tid = res.data.tid
        if (this.fileList.length !== 0) {
          for (const file of this.fileList.map(item => item.raw)) {
            const formData = new FormData()
            formData.append('file', file)
            await uploadOrderFile(formData, tid).then(res => {
            })
          }
          await publishDraft(tid).then(res => {
            this.$message.success('发布表单成功')
          }).catch(() => {
            deleteDraft(tid).then(res => {
            })
          })
          this.$message.success('添加表单草稿成功')
          setTimeout(() => {
            this.$router.push('/workOrderSys/myDraft')
          }, 500)
        } else {
          publishDraft(tid).then(res => {
            this.$message.success('发布表单成功')
            setTimeout(() => {
              this.$router.push('/workOrderSys/myCreation')
            }, 500)
          }).catch(() => {
            deleteDraft(tid).then(res => {
            })
          })
        }
        loadingInstance.close()
      })
    },
    searchUser(page) {
      this.listLoading = true
      findUser(5, page, {name: this.queryUser.keyword}).then(response => {
        this.searchList = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    searchMainOrder(page) {
      this.childOrderListLoading = true
      let param = {
        name: this.queryChildOrder.keyword,
        filter: -1,

      }
      getMyCreatedOrderList(PAGE_SIZES, page, param).then(response => {
        this.childOrderList = response.data.data.filter(item => item.type === 1)
        this.childOrderTotal = response.data.total
        this.childOrderListLoading = false
      })
    },
    getBodyValue() {
      for (let item of this.bodyRenderList) {
        if (item.json != null) {
          this.bodyModelValue[`${item.oid}`] = this.$refs[`${item.oid}`][0].getFormData(false)
        }
      }
    },
    saveAsDraft() {
      this.getBodyValue()
      const header = this.$refs.Header.getFormData(false)
      this.template.body_list.forEach((item, index) => {
        this.bodyModelValue[item].num = index + 1
      })
      const data = {
        name: header.projectName || header.retData.projectName,
        handler: this.$store.getters.userInfo.uid,
        header_id: this.template.header_id,
        header_value: header,
        body_list: this.template.body_list,
        body_value: this.bodyModelValue,
        tail_id: this.template.tail_id,
        tail_value: this.$refs.Tail.getFormData(false)
      }
      addDraft(data).then(async res => {
        const loadingInstance = this.$loading({fullscreen: true})
        const tid = res.data.tid
        if (this.fileList.length !== 0) {
          for (const file of this.fileList.map(item => item.raw)) {
            const formData = new FormData()
            formData.append('file', file)
            await uploadOrderFile(formData, tid).then(res => {
            })
          }
          this.$message.success('添加表单草稿成功')
          setTimeout(() => {
            this.$router.push('/workOrderSys/myDraft')
          }, 500)
        } else {
          this.$message.success('添加表单草稿成功')
          setTimeout(() => {
            this.$router.push('/workOrderSys/myDraft')
          }, 500)
        }
        loadingInstance.close()
      })
    },
    fetchData() {
      this.listLoading = true
      getTemplateList(1, 1, {name: this.$route.query.name}).then(res => {
        this.template = res.data.data[0]
        const info = res.data.data[0]
        if (info.description) {
          const {header, tail} = JSON.parse(info.description)
          if (header.hasOwnProperty('retData')) {
            this.headerFormOrigin = header.retData
            this.tailForm = tail.retData
          } else {
            if (!Array.isArray(header.config)) {
              if (parseFloat(header.config).toString() === 'NaN') {
                header.configCustom = header.config
                header.config = []
              } else {
                header.config = [header.config]
                header.configCustom = ''
              }
              this.headerFormOrigin = header
              this.tailForm = tail
            }
          }
          this.chooseHeader = this.headerTemplates.find((item) => {
            return item.oid === info.header_id
          })
          this.chooseTail = this.tailTemplates.find((item) => {
            return item.oid === info.tail_id
          })
        }
        this.template.body_list.forEach((item, index) => {
          this.bodyModelValue[`${item}`] = {}
          const find = this.bodyTemplates.find(i => i.oid === item)
          this.bodyRenderList.push(find)
        })
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}

</style>

